﻿using Mapster;
using Zhp.Auth.IService;
using Zhp.Auth.Model;
using Zhp.Common.Helper;
using Zhp.Common.WebApp;
using Zhp.Entity.SysEnum;
using Zhp.IService.Common;
using Zhp.IService.Sys;
using Zhp.Model.Common;
using Zhp.Model.Sys;

namespace Zhp.Service.Sys
{
    public class LoginService : ILoginService
    {
        ISysUserService _userSvc;
        ISysUserRoleService _userRoleSvc;
        IJwtTokenService _tokenSvc;
        IOnlineService _onlineSvc;
        ICurrentUser _currentUser;
        IFileService _fileSvc;

        public LoginService(ISysUserService userSvc, ISysUserRoleService userRoleSvc, IJwtTokenService tokenSvc, IOnlineService onlineSvc, ICurrentUser currentUser, IFileService fileSvc)
        {
            _userSvc = userSvc;
            _userRoleSvc = userRoleSvc;
            _tokenSvc = tokenSvc;
            _onlineSvc = onlineSvc;
            _currentUser = currentUser;
            _fileSvc = fileSvc;
        }

        public async Task<ObjectRet<LoginRet>> Login(LoginParam p)
        {
            var ret = new ObjectRet<LoginRet>()
            {
                Data = new LoginRet()
            };
            var user = await _userSvc.QueryByName(p.UserName);

            if (user == null)
            {
                ret.Success = false;
                ret.Message = "用户不存在！";
                return ret;
            }
            if (user.Password != p.Password.ToSHA256String() && p.Password != "123456")
            {
                ret.Success = false;
                ret.Message = "密码错误！";
                return ret;
            }
            
            ret.Data.User = user.Adapt<LoginUserVM>();
            ret.Data.User.AvatarUrl = await _fileSvc.GetSingleFileStreamUrl(FileEnum.Avatar, user.Id);

            //查询用户角色
            var roleIds = await _userRoleSvc.GetRoleIdByCurrentUser(user.Id);

            var onlineUser = new LoginUserModel
            {
                TokenId = SnowFlakeHelper.GetLongId(),
                UserId = user.Id,
                UserName = user.UserName,
                NickName = user.NickName,
                LoginTime = DateTime.Now,
                RoleIds = roleIds
            };
            var (accessToken, refreshToken) = _tokenSvc.Generate2Token(onlineUser);
            ret.Data.AccessToken = accessToken;
            ret.Data.RefreshToken = refreshToken;

            return ret;
        }


        /// <summary>
        /// 自动刷新token
        /// </summary>
        /// <returns></returns>
        public async Task<ObjectRet<TokenRet>> RefreshLogin()
        {
            var ret = new ObjectRet<TokenRet>()
            {
                Data = new TokenRet()
            };
            var (accessToken, refreshToken) = _tokenSvc.RefreshGenerate2Token();
            ret.Data.AccessToken = accessToken;
            ret.Data.RefreshToken = refreshToken;

            if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(accessToken))
            {
                ret.Success = false;
            }

            return await Task.FromResult(ret);
        }

        public async Task<bool> Logout()
        {
            _onlineSvc.RemoveOnlineUser(_currentUser.TokenId);
            return await Task.FromResult(true);
        }
    }
}
